
import "../style/list.css";
import "../style/create.css";
import { getRequestParameter } from "./request";
import { EUV } from "@hongweifei/euv";
import { StatusCode } from "../api/web-result";
import { getUserInfo, logout as userLogout } from "../api/user";
import {
    Question,
    QuestionType,
    WJ,
    getWJByUsernameAndTitle,
    createWJ as requestCreateWJ,
    updateWJ as requestUpdateWJ,
} from "../api/wj";


const app = new EUV({
    elementSelector: "#app",
    async mounted() {
        setInterval(() => {
            const date = new Date();
            this.data.nowDate = date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        }, 500);

        const userInfoResult = await getUserInfo();
        if (userInfoResult.code !== StatusCode.SUCCESS) {
            alert(userInfoResult.message);
            window.location.href = "../index.html";
            return;
        }
        const user = userInfoResult.data;
        if (!user) {
            alert("错误");
            window.location.href = "../index.html";
            return;
        }
        this.data.user = user;
        this.data.login = true;
    },

    data: {
        nowTime: (function() {
            const date = new Date();
            return date.toLocaleDateString() + "    " + date.toLocaleTimeString();
        })(),
        user: {},
        login: false,
    },

    methods: {
        logout() {
            userLogout();
            this.data.user = {};
            this.data.login = false;
            window.location.reload();
        },
    }
});





// 功能实现相关代码
// 相关元素
const questionTypeListElement = document.querySelector("#list-question-type");
const wjTitleInputElement = document.querySelector(".input-wj-title");
const wjDescriptionInputElement = document.querySelector(".input-wj-description");

// 判断是 create 还是 update
const Action = {
    CREATE: "create",
    UPDATE: "update"
}
let action = Action.CREATE;
let updateWJ = undefined;

// 问卷相关
const questionTypes = [
    QuestionType.SINGLE_CHOICE,
    QuestionType.MULTIPLE_CHOICE,
    QuestionType.JUDGEMENT,
    QuestionType.FILL_IN_THE_BLANK,
    QuestionType.SHORT_ANSWER,
];
const questionDataSource = [];
const questionFormElement = document.querySelector("#form-question");
const questionTemplate = document.querySelector("#template-question").content.children[0];


const parameterObj = getRequestParameter();
if (parameterObj["action"] &&  parameterObj["action"] === Action.UPDATE) {
    document.querySelector(".container-button-create").querySelector("input").value = "修改问卷";
    action = parameterObj["action"];
    if (!parameterObj["title"]) {
        alert("参数错误");
        window.history.back();
    }
    (async function(){
        const userInfoResult = await getUserInfo();
        const userInfo = userInfoResult.data;
        const creator = userInfo.username;
        const wjResult = await getWJByUsernameAndTitle(creator, parameterObj["title"]);
        if (wjResult.code !== StatusCode.SUCCESS) {
            alert(wjResult.message);
            window.history.back();
        }
        updateWJ = wjResult.data;
        wjTitleInputElement.value = updateWJ.title;
        wjDescriptionInputElement.value = updateWJ.description;
        updateWJ.question.forEach(q => addQuestion(q));
    }());
}




function addQuestionByType(questionType) {
    const q = new Question(
        "",
        "",
        questionType,
        []
    );
    return addQuestion(q);
}
/**
 * @param { Question } question
 */
function addQuestion(question) {
    const questionType = question.type;
    console.log(questionType);
    if (
        questionType.value === "填空题" ||
        questionType.value === "简答题"
    ) {
        alert("暂不支持");
        return;
    }

    const questionIndex = questionDataSource.push(question) - 1;
    /** @type { HTMLElement } */
    const questionElement = questionTemplate.cloneNode(true);
    questionElement.querySelector("h3").textContent = questionType.value;
    const titleInputElement = questionElement.querySelector(".input-title");
    titleInputElement.value = question.title;
    titleInputElement.onchange = () => {
        questionDataSource[questionIndex].title = titleInputElement.value;
    }
    const descriptionInputElement = questionElement.querySelector(".input-description");
    descriptionInputElement.value = question.description;
    descriptionInputElement.onchange = () => {
        questionDataSource[questionIndex].description = descriptionInputElement.value;
    }

    const addOptionItem = (optionIndex) => {
        const li = document.createElement("li");
        const input = document.createElement("input");
        input.value = questionDataSource[questionIndex].content[optionIndex];
        input.required = true;
        input.onchange = () => {
            questionDataSource[questionIndex].content[optionIndex] = input.value;
        }
        li.appendChild(input);
        questionElement.querySelector(".list-option").appendChild(li);
    }
    // 添加选项
    for (let i = 0; i < question.content.length; i++) {
        addOptionItem(i);
    }

    const tempPush = question.content.push;
    question.content.push = function(...args) {
        const optionIndex = question.content.length;
        tempPush.apply(question.content, args);
        addOptionItem(optionIndex);
    };

    questionElement.querySelector(".button-add-option").onclick = () => {
        addOption(questionIndex);
    };
    questionElement.querySelector(".button-remove").onclick = () => {
        removeQuestion(questionIndex);
        questionElement.remove();
    }
    questionFormElement.appendChild(questionElement);

    return questionIndex;
}
function removeQuestion(questionIndex) {
    questionDataSource.splice(questionIndex, 1);
}

function addOption(questionIndex) {
    console.log("题目", questionIndex, "添加选项");
    questionDataSource[questionIndex].content.push("");
}

function createOrUpdateWJ() {
    if (action === Action.UPDATE) {
        console.log("更新问卷");
    } else {
        console.log("创建问卷");
    }
    if (questionDataSource.length === 0) {
        alert("问卷至少包含一个问题");
        return;
    }

    for (const q of questionDataSource) {
        if (!q.title) {
            alert("题目标题不能为空");
            return;
        }
        if (q.content.length < 2) {
            alert("题目选项不能少于两个");
            return;
        }
        for (const option of q.content) {
            if (!option) {
                alert("题目选项不能为空");
                return;
            }
        }
    }

    const wj = new WJ (
        app.data.user.username,
        wjTitleInputElement.value,
        wjDescriptionInputElement.value,
        questionDataSource
    );
    console.log(wj);
    if (action === Action.UPDATE) {
        requestUpdateWJ(wj)
        .then(result => {
            alert(result.message);
            if (result.code === StatusCode.SUCCESS) {
                window.history.back();
            }
        });
    } else {
        requestCreateWJ(wj)
        .then(result => {
            alert(result.message);
            if (result.code === StatusCode.SUCCESS) {
                window.history.back();
            }
        });
    }
}



if (questionTypeListElement) {
    questionTypes.forEach((type) => {
        const li = document.createElement("li");
        li.className = "list-item button text-center"
        li.textContent = type.value;

        li.onclick = () => {
            addQuestionByType(type);
        };
        questionTypeListElement.appendChild(li);
    });
}


questionFormElement.onsubmit = (e) => {
    e.preventDefault();
    createOrUpdateWJ();
};

